const Koa = require('koa');
const app = new Koa();

const router = require('@koa/router')()
const bodyParser = require('koa-bodyparser');

const global = require('./utils/mysql')

// 获取数据的接口
router.get('/list', async (ctx) => {
    // let data = [];
    // await global.query(`select * from address`)
    //     .then(result => {
    //         data = result
    //     })
    //     .catch(err => {
    //         console.log(err);
    //     })
    // ctx.body = {
    //     code: 1,
    //     data,
    //     msg: '请求成功',
    // }

    let data = await global.query(`select * from address`)
    ctx.body = {
        code: 1,
        data,
        msg: '请求成功',
    }
})

// 添加的接口
router.post('/list/add', async (ctx) => {
    let { name, duty, defaults, voince, type, email } = ctx.request.body;

    // if (!type || !name || !defaults) {
    //     ctx.body = { code: -1, msg: '参数不合' };
    //     return;
    // }
    let data = await global.query(`insert into address(name,duty,defaults,voince,type,email) values('${name}','${duty}',${defaults},${voince},${type},${email})`);
    if (data.code == 1) {
        ctx.body = {
            code: 1,
            msg: '添加成功',
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '添加失败',
        }
    }
})

app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(4000, () => {
    console.log("http://localhost:4000 启动成功");
});